package project_phase1;

import java.util.Vector;

public class ContactList extends Vector<Contact> {
	private static final long serialVersionUID = 1L;

	private int findCursor = 0;//starting point for find
	
	public Contact addContact(String firstName, String middleName, String lastName, String dob) throws IllegalArgumentException {
		Contact newContact = new Contact(firstName, middleName, lastName, dob);
		this.add(newContact);
		return newContact;
	}
	
	public Contact findContact(String criteria, int fieldType) throws IllegalArgumentException {
		findCursor = 0;
		return findNextContact(criteria, fieldType);
	}
	
	public Contact findNextContact(String criteria, int fieldType) throws IllegalArgumentException {
		for(int i = findCursor; i < this.size(); i++) {
			Contact contact = (Contact) this.get(i);
			switch(fieldType) {
				case Contact.FIELD_FIRSTNAME :
					if(contact.getFirstName().contains(criteria)) {
						findCursor = i + 1;
						return contact;
					}
					break;
				case Contact.FIELD_LASTNAME :
					if(contact.getLastName().contains(criteria)) {
						findCursor = i + 1;
						return contact;
					}
					break;
				case Contact.FIELD_MIDDLENAME :
					if(criteria == null) {
						if(contact.getMiddleName() == null) {
							findCursor = i + 1;
							return contact;
						} else
							break;
					}
					if(contact.getMiddleName() == null)
						break;
					if(criteria.length() == 0) {
						if(contact.getMiddleName().length() == 0) {
							findCursor = i + 1;
							return contact;
						} else
							break;
					}
					if(contact.getMiddleName().contains(criteria)) {
						findCursor = i + 1;
						return contact;
					}
					break;
				case Contact.FIELD_DOB :
					Contact testContact = null;
					try {
						testContact = new Contact("a", "", "b", criteria);
					} catch(Exception e) {
						throw new IllegalArgumentException("DOB should be string in format of mm/dd/yyyy !");
					}
					if(contact.getFormattedDOB().equalsIgnoreCase(testContact.getFormattedDOB())) {
						findCursor = i + 1;
						return contact;
					}
					break;
			}
		}
		findCursor = 0;//reset find cursor
		return null;
	}
	
	public String toString() {
		String ret = "Contact List contents:\n";
		if(this.size() > 0) {
			for(Contact contact : this) 
				ret += contact.toString() + "\n";
		} else
			ret += "no contacts\n";
		return ret;
	}

}
